<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js';
import { debounce } from 'lodash';
export default {
  name: 'searchSuggestion',
  data() {
    return {
      suggestions: [] // 联想建议数据列表
    };
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      // 当 searchText 发生改变的时候就会调用 handler 方法
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value);
      }, 1000),
      // 该回调将会在侦听开始以后被立即调用
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (error) {
        this.$toast('获取数据失败, 请稍后重试');
      }
    },
    highlight(text) {
      if (!text) return;
      console.log(text);
      const highlight = `<span class="active">${this.searchText}</span>`;
      const reg = new RegExp(this.searchText, 'gi');
      return text.replace(reg, highlight);
    }
  }
};
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ .active {
    color: seagreen;
  }
}
</style>
